package com.kmproject.haifu.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.di.component.DaggerPersonalSenondHandComponent;
import com.kmproject.haifu.mvp.contract.PersonalSenondHandContract;
import com.kmproject.haifu.mvp.model.entity.beans.SecondHandInfoBean;
import com.kmproject.haifu.mvp.model.entity.resbean.SecondHandQueryParmar;
import com.kmproject.haifu.mvp.presenter.PersonalSenondHandPresenter;
import com.kmproject.haifu.mvp.ui.activity.SecondHandListShowActivity;
import com.kmproject.haifu.mvp.ui.adapter.SecondHandMainShowAdapter;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.PullToRefreshView;
import com.library.flowlayout.SpaceItemDecoration;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 09/05/2019 10:21
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class PersonalSenondHandFragment extends BaseFragment<PersonalSenondHandPresenter> implements PersonalSenondHandContract.View {
    private static final String USER_ID = "userId";
    private static final String ACCOUNT_TYPE = "accountType";
    @BindView(R.id.PersonalSenondHand_RecyclerView)
    RecyclerView PersonalSenondHandRecyclerView;
    @BindView(R.id.PersonalSenondHand_RecyclerView_PullToRefreshView)
    PullToRefreshView PersonalSenondHandRecyclerViewPullToRefreshView;
    Unbinder unbinder;
    SecondHandMainShowAdapter secondHandMainShowAdapter;
    private String muserID;
    SecondHandQueryParmar secondHandQueryParmar =new SecondHandQueryParmar();
    /**
     * @param userId      accountType传入0时，userId为用户id；accountType传入1时，userId为店铺id
     * @param accountType 账号类型0-用户；1-店铺
     * @return
     */
    public static PersonalSenondHandFragment newInstance(String userId, int accountType) {

        PersonalSenondHandFragment fragment = new PersonalSenondHandFragment();
        Bundle args = new Bundle();
        args.putString(USER_ID, userId);
        args.putInt(ACCOUNT_TYPE, accountType);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerPersonalSenondHandComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_personal_senond_hand, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        muserID=getArguments().getString(USER_ID);
        PersonalSenondHandRecyclerViewPullToRefreshView.setEnableRefresh(false);//禁止下拉刷新
        secondHandMainShowAdapter=new SecondHandMainShowAdapter(new ArrayList<>());
        PersonalSenondHandRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        PersonalSenondHandRecyclerView.addItemDecoration(new SpaceItemDecoration(AppUtil.dp2px(10)));
        secondHandMainShowAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        PersonalSenondHandRecyclerView.setAdapter(secondHandMainShowAdapter);

        mPresenter.userSecondHand(muserID,secondHandQueryParmar);
        PersonalSenondHandRecyclerViewPullToRefreshView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                secondHandQueryParmar.setPage(secondHandQueryParmar.getPage()+1);
                mPresenter.userSecondHand(muserID,secondHandQueryParmar);
            }
        });
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    public void userSecondHandSuccess(int curryPage, int totalPage, List<SecondHandInfoBean> secondHandInfoBeans) {
        PersonalSenondHandRecyclerViewPullToRefreshView.finishLoadMore();
        if (secondHandInfoBeans == null || secondHandInfoBeans.isEmpty()) {
            PersonalSenondHandRecyclerViewPullToRefreshView.setEnableLoadMore(false);
            if (curryPage == 1) {
                secondHandMainShowAdapter.setEmptyView(AppUtil.setEmptyView(getActivity(), "没有搜索到相关信息，换个条件试试", "", null, true));
            }
            return;
        }
        secondHandQueryParmar.setPage(curryPage);
        if (curryPage >= totalPage) {
            PersonalSenondHandRecyclerViewPullToRefreshView.setEnableLoadMore(false);
        } else {
            PersonalSenondHandRecyclerViewPullToRefreshView.setEnableLoadMore(true);
        }
        if (secondHandMainShowAdapter.getData() == null || secondHandMainShowAdapter.getData().isEmpty()) {
            secondHandMainShowAdapter.setNewData(secondHandInfoBeans);
        } else {
            secondHandMainShowAdapter.addData(secondHandInfoBeans);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
